package com.ltmonitor.web.controller.command;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.JT809Command;
import com.ltmonitor.service.IJT809CommandService;
import com.ltmonitor.service.ITerminalService;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;

/**
 * 平台间报文
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/platformPostQuery")
public class PlatformPostQueryAction extends GenericAction {
	

	@Autowired
	private IJT809CommandService jt809CommandService;


	/**
	 * 获取查岗信息，并显示在前台窗口
	 */
	@RequestMapping("/view.action")
	public String viewPostQuery(long commandId, Model m) {
		Map<String,Object> entity = new HashMap();
		String message = "";
		try {
			JT809Command tc = this.jt809CommandService.load(commandId);
			if (tc != null) {
				String[] msg = tc.getCmdData().split(";");
				entity.put("infoId", msg[0]);
				entity.put("objId", msg[1]);
				String objType = "" + msg[2];
				String objTypeDescr = this.convert(objType, "PostQueryType");
				entity.put("objType", objType);
				entity.put("objTypeDescr", objTypeDescr);
				entity.put("content", msg[3]);
				entity.put("commandId", commandId);
				entity.put("platformId", tc.getUserId());

			} else
				message = ("没有找到查岗命令");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			message = (e.getMessage());
		}
		m.addAttribute("entity", entity);
		m.addAttribute("message", message);

		return "/command/postQuery";
	}

	
	
	/**
	 * 查岗应答
	 * @param platformId 如果809连接多个上级平台，应答时需要判断是那个平台的，只给对应平台进行应答
	 * @param infoId
	 * @param objId
	 * @param content
	 * @param objType
	 * @param answer
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/send.action")	
	public JsonMessage send(long platformId,String infoId,String objId,String content,String objType,String answer) {
		try {
			JT809Command jc = new JT809Command();
			jc.setCmd(0x1300);
			jc.setSubCmd(0x1301);
			StringBuilder sb = new StringBuilder();
			sb.append(objType).append(";").append(objId).append(";")
					.append(infoId).append(";").append(answer);
			jc.setCmdData(sb.toString());
			if (platformId == 0)
				platformId = this.getOnlineUser().getEntityId();
			jc.setUserId(platformId);
			OnlineUser onlineUser = getOnlineUser();
			if (onlineUser != null) {
				jc.setOwner(onlineUser.getName());
				// jc.setUserId(onlineUser.getEntityId());
			}
			this.jt809CommandService.save(jc);
			return json(true, "");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}
	}

	

}
